package com.study.manage.repository;

import com.study.manage.entity.PermissionVO;
import com.study.manage.pojo.UserRoleKey;
import org.hibernate.Session;
import org.hibernate.query.NativeQuery;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import java.util.List;

@Repository
public class EntityManagerRepository {
    @PersistenceContext
    private EntityManager entityManager;

    /**
     * 根据用户id获取權限数据
     * @param id
     * @return
     */
    @Transactional
    public List<PermissionVO> findPermsByUserId(Integer id) {
        String sql = "select p.id, p.name,p.pid pId, p.istype, p.code,p.page, p.icon, p.zindex from permission p " +
                "LEFT JOIN role_permission rp ON rp.permit_id=p.id " +
                "LEFT JOIN role r ON r.id=rp.role_id " +
                "LEFT JOIN user_role ur ON ur.role_id=r.id " +
                "WHERE ur.user_id= :id GROUP BY p.id order by p.zindex";

        EntityManager em = entityManager.getEntityManagerFactory().createEntityManager();

        Session session = em.unwrap(Session.class);
        NativeQuery query = session.createNativeQuery(sql).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.aliasToBean(PermissionVO.class));

        query.setParameter("id", id);
        List<PermissionVO> list = query.list();
        em.close();

        return list;
    }

    @Transactional
    public List<UserRoleKey> findUserRoleByUserId(Integer id) {
        String sql = "select r.user_id userId, r.role_id roleId" +
                " from user_role as r " +
                " where r.user_id =:id";

        //EntityManager 并不是单实例的，每调用一次由 EntityManagerFactory 创建一个 EntityManager 对象。用完之后就关闭扔掉，或者是还回到池中去了。
        EntityManager em = entityManager.getEntityManagerFactory().createEntityManager();  //作用是啥？
        Session session = em.unwrap(Session.class);
        NativeQuery query = session.createNativeQuery(sql).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.aliasToBean(UserRoleKey.class));

        query.setParameter("id", id);
        List<UserRoleKey> list = query.list();
        em.close();

        return list;
    }
}
